import {
    Card,
    Breadcrumb,
    Form,
    Button,
    Radio,
    Input,
    Upload,
    Space,
    Select
} from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import { Link, useSearchParams,useNavigate } from 'react-router-dom'
import './index.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { useEffect, useState } from 'react'
import { message } from 'antd'
import { PublishApi } from '@/apis/articles'
import useChannels from '@/hooks/useChannels'
import {GetarticleApi,UpArticleApi} from '@/apis/articles'

const { Option } = Select

const Publish = () => {
    const {channels} =  useChannels()
    const [parms] = useSearchParams()
    const articleId = parms.get('id')
    const navigate = useNavigate()

    //发布文章
    const onFinish = (formValue) => {

        if(imgageType !== imageList.length){
            message.warning("上传图片数量和选择项不匹配！")
            return
        }

        const { title, channel_id, content } = formValue
        const data = {
            channel_id,
            status:1,
            content,
            title,
            type: 1,
            cover: {          //cover：文章封面
                type: imgageType,      //type:封面类型 0：无图 1：1图 3:3图
                //images：文章封面图片地址数组
                images: imageList.map(item=>{
                    if (item.response){
                        return item.response.data.url
                    }else{
                        return item.url
                    }
                })
            }
        }
        console.log("publish data:", data)
        const articlePublish = async () => {
            try {
                await PublishApi(data)
                navigate('/article')
                message.success('发布文章成功')
            } catch (error) {
                console.log("error:", error)
            }
        }
        const UpArticlePublish = async () => {
            try {
                await UpArticleApi(data,articleId)
                navigate('/article')
                message.success('更新文章成功')
            } catch (error) {
                console.log("error:", error)
            }
        }

        if (articleId){
            UpArticlePublish()
        }else{
            articlePublish()
        }
    }

    //上传图片文件列表缓存
    const [cachImageList,setCachImageList] = useState([])
    // 上传图片
    const [imageList, setImageList] = useState([])
    const onUploadChange = (info) => {
        setImageList(info.fileList)
        setCachImageList(info.fileList)
    }

    //单选框value
    const [imgageType,setImageType] = useState(0)
    const onTypeChange = (e)=>{
        const type = e.target.value
        setImageType(type)
        if(type === 1){
            const imgList = cachImageList[0]?[cachImageList[0]]:[]
            setImageList(imgList)
        }else if(type === 3){
            setImageList(cachImageList)
        }else{
            setImageList([])
        }
    }

    const [form] = Form.useForm()
    //更新时获取文章数据
    useEffect(()=>{
        const getArticle = async ()=>{
            console.log(articleId)
            const res = await GetarticleApi(articleId)
            const article = res.data.results[0]
            form.setFieldsValue({
                ...article,
                type:article.cover.type,
            })
            setImageType(article.cover.type)
            setImageList(article.cover.images.map(image=>({"url":image})))
            setCachImageList(article.cover.images.map(image=>({"url":image})))
        }
        if(articleId){
            getArticle()
        }
    },[articleId,form])

    return (
        <div className="publish">
            <Card
                title={
                    <Breadcrumb items={[
                        { title: <Link to={'/'}>首页</Link> },
                        { title: `${articleId ? '更新文章' : '发布文章'}` },
                    ]}
                    />
                }
            >
                <Form
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 16 }}
                    initialValues={{ type: 0 }}
                    onFinish={onFinish}
                    form={form}
                >
                    <Form.Item
                        label="标题"
                        name="title"
                        rules={[{ required: true, message: '请输入文章标题' }]}
                    >
                        <Input placeholder="请输入文章标题" style={{ width: 400 }} />
                    </Form.Item>
                    <Form.Item
                        label="频道"
                        name="channel_id"
                        rules={[{ required: true, message: '请选择文章频道' }]}
                    >
                        <Select placeholder="请选择文章频道" style={{ width: 400 }}>
                            {channels.map(item => <Option key={item.id} value={item.channel_id}>{item.channel}</Option>)}
                        </Select>
                    </Form.Item>
                    <Form.Item label="封面">
                        <Form.Item name="type">
                            <Radio.Group onChange={onTypeChange}>
                                <Radio value={1}>单图</Radio>
                                <Radio value={3}>三图</Radio>
                                <Radio value={0}>无图</Radio>
                            </Radio.Group>
                        </Form.Item>
                        {imgageType > 0 && <Upload
                            name="image"
                            listType="picture-card"
                            showUploadList
                            action={'http://localhost/geek/upload'}
                            onChange={onUploadChange}
                            maxCount={imgageType}
                            multiple={imgageType > 1}
                            fileList={imageList}
                        >
                            <div style={{ marginTop: 8 }}>
                                <PlusOutlined />
                            </div>
                        </Upload>}
                    </Form.Item>
                    <Form.Item
                        label="内容"
                        name="content"
                        rules={[{ required: true, message: '请输入文章内容' }]}
                    >
                        <ReactQuill
                            className="publish-quill"
                            theme="snow"
                            placeholder="请输入文章内容"
                        />
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Space>
                            <Button size="large" type="primary" htmlType="submit">
                                {articleId ? "更新文章":"发布文章"}
                            </Button>
                        </Space>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    )
}

export default Publish